package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {
    /**
     * 前置处理    获取用户信息，存入线程中
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取登录用户的id
        String userId = request.getHeader("userId");
        //1.1排除登录请求
        String path = request.getRequestURI().toString();
        if (path.contains("in")){
            return true;
        }

        //2.判断是否存在
        if (StringUtils.isEmpty(userId)){
            log.error("当前用户没有登录,请求被WmTokenInterceptor阻止了");
            return false;
        }
        //3.如果存在则创建WmUser对象设置他的id并存入到ThreadLocal中
        WmUser wmUser = new WmUser();
        wmUser.setId(Integer.parseInt(userId));
        WmThreadLocalUtil.add(wmUser);
        return true;
    }

    /**
     * 后置处理，清理threadlocal中的数据，防止内存溢出
     *
     * @param request
     * @param response
     * @param handler
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //清空数据
        WmThreadLocalUtil.remove();

    }
}
